from time import time
from imp import load_source
from operator import attrgetter
from inspect import isclass
from agents import agent_classes
from core.agent import Agent

class AgentManager(dict):
    """Manager to import and modify agent files."""

    def __init__(self):
        self.load_default()
        
    def load_default(self):
        """Load the default agents"""
        self.clear()
        self.update(dict([(x.__name__,x) for x in agent_classes]))

    def classes(self):
        """Get list of agent classes sorted by class name"""
        return sorted(self.values(), key=attrgetter('__name__'))

    def names(self):
        """Get sorted list of agent names"""
        return sorted(self.keys())
        
    def load_file(self, path):
        """
        Load agent classes contained in file at path, if any.
        Returns a list of the imported class names.
        """
        result = []
        tmp = 'd' + str(time()).replace('.','_')
        try:
            module = load_source(tmp,path)
        except:
            raise
        for cname in dir(module):
            if cname[:2] != '__' and cname != 'Agent':
                c = getattr(module,cname)
                if isclass(c) and issubclass(c,Agent):
                    self[c.__name__] = c
                    result.append(c.__name__)
        return result

    def test_agent(self,agent_class):
        """For agent debugging purposes"""
        pass
